<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
defer 1
</h1>
<p></p>
<div id="question" class="tmd-base">
<div class="tmd-usual">
What does the following program print?
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

type Foo struct {
	v int
}

func MakeFoo(n *int) Foo {
	print(*n)
	return Foo{}
}

func (Foo) Bar(n *int) {
	print(*n)
}

func main() {
	var x = 1
	var p = &amp;x
	defer MakeFoo(p).Bar(p) // line 19
	x = 2
	p = new(int) // line 21
	MakeFoo(p)
}
</code></pre>
</div>
<p></p>
<div class="tmd-usual">
Choices:
</div>
<p></p>
<input type="radio" id="choiceA" name="choice" class="choice">
<input type="radio" id="choiceB" name="choice" class="choice">
<input type="radio" id="choiceC" name="choice" class="choice">
<input type="radio" id="choiceD" name="choice" class="choice">

<div id="choices">

<ul style="list-style-type:none;">
<li><label for="choiceA">100</label></li>
<li><label for="choiceB">102</label></li>
<li><label for="choiceC">022</label></li>
<li><label for="choiceD">011</label></li>
</ul>

</div><p></p>
<div id="answer" class="tmd-base">
<div class="tmd-usual">
Answer: 102
</div>
<p></p>
<div class="tmd-usual">
Run it on <a href="https://go.dev/play/p/WfuL8NQ4HKA">Go play</a>.
</div>
<p></p>
<div class="tmd-usual">
Key points:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
When a function call is pushed into the deferred call queue, the called function value and all the arguments are evaluated. The evaluated values will be used when the call is executed later in the existing phase of its caller function.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
So, at line 19, when the deferred call <code class="tmd-code-span">Bar</code> is pushed into the deferred call queue, its arguments <code class="tmd-code-span">MakeFoo(p)</code> (as the receiver argument) and <code class="tmd-code-span">p</code> are evaluated. In evaluating <code class="tmd-code-span">MakeFoo(p)</code>, <code class="tmd-code-span">1</code> is printed.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The later modification at line 21 doesn't affect the evaluation results at line 19, which means the argument passed to the <code class="tmd-code-span">Bar</code> function call is still a pointer to the variable <code class="tmd-code-span">x</code>.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
A similar quiz:
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

type T int

func (t T) M(n int) T {
	print(n)
	return t
}

func main() {
	var t T
	defer t.M(1).M(2)
	t.M(3).M(4)
}
</code></pre>
<p></p>
<div class="tmd-usual">
The above quiz program prints <code class="tmd-code-span">1342</code>.
</div>
<p></p>
</div>
<p></p>
</div>
